#include "addsheguan.h"
#include "ui_addsheguan.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QDebug>
#include "dbmanager.h"
addsheguan::addsheguan(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::addsheguan)
{
    ui->setupUi(this);
}

addsheguan::~addsheguan()
{
    delete ui;
}

// 数据库连接辅助函数
bool addsheguan::openDatabase()
{
    QSqlDatabase db = DBManager::instance()->getDatabase();

    if (!db.open()) {
        QMessageBox::critical(this, "错误", "数据库连接失败: " + db.lastError().text());
        qDebug() << "数据库连接失败: " << db.lastError().text();
        return false;
    }
    return true;
}

// 清空输入框（可选）
void addsheguan::clearInputFields()
{
    ui->lineEdit_sheid->clear();
    ui->lineEdit_shename->clear();
    ui->lineEdit_shegender->clear();
    ui->lineEdit_contact1->clear();
    ui->lineEdit_building1->clear();
    ui->lineEdit_password1->clear();
}

// 添加按钮点击事件
void addsheguan::on_pushButton_addshe_clicked()
{
    // 获取输入框内容
    QString sheId = ui->lineEdit_sheid->text().trimmed();       // 工号
    QString sheName = ui->lineEdit_shename->text().trimmed();   // 姓名
    QString sheGender = ui->lineEdit_shegender->text().trimmed(); // 性别
    QString contact = ui->lineEdit_contact1->text().trimmed();   // 联系方式
    QString building = ui->lineEdit_building1->text().trimmed(); // 宿舍楼号
    QString password = ui->lineEdit_password1->text().trimmed(); // 密码

    // 输入校验
    if (sheId.isEmpty() || sheName.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "错误", "工号、姓名和密码不能为空！");
        return;
    }

    // 连接数据库
    if (!openDatabase()) return;

    // 构建插入语句（使用预处理防止SQL注入）
    QSqlQuery query;
    query.prepare("INSERT INTO dormmanager (manager_id, manager_name, gender, contact, building, login_password) "
                  "VALUES (:id, :name, :gender, :contact, :building, :password)");

    query.bindValue(":id", sheId);
    query.bindValue(":name", sheName);
    query.bindValue(":gender", sheGender);
    query.bindValue(":contact", contact);
    query.bindValue(":building", building);
    query.bindValue(":password", password); // 建议存储密码哈希值，而非明文

    // 执行插入
    if (query.exec()) {
        QMessageBox::information(this, "成功", "舍管信息添加完成！");
        clearInputFields(); // 清空输入框（可选函数）
        emit addSuccess(); // 可添加信号通知主窗口刷新数据
    } else {
        QMessageBox::critical(this, "错误", "添加失败: " + query.lastError().text());
        qDebug() << "SQL错误: " << query.lastError().text();
    }
}



void addsheguan::on_pushButton_exit_clicked()
{
    this->close();
}

